package atom.core3.spring.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.util.StopWatch;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

//interceptor不是线程安全的 我们需要借助threadlocal来实现线程安全
public class PageDebugInterceptor implements HandlerInterceptor
{
	// 日志
	private static Logger logger = Logger.getLogger(PageDebugInterceptor.class);
	private static ThreadLocal<StopWatch>	stopWatchLocal	= new ThreadLocal<StopWatch>();

	// 方法调用前调用
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{
		StopWatch stopWatch = new StopWatch(handler.toString());
		stopWatchLocal.set(stopWatch);
		stopWatch.start(handler.toString());
		return true;
	}

	// 方法调用时，在view render之前的调用
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView view)
	        throws Exception
	{
	}

	// 调用结束后，已经view render了之后的clean操作
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
	        throws Exception
	{

		StopWatch stopWatch = stopWatchLocal.get();
		stopWatch.stop();
		String currentPath = request.getRequestURI();
		String queryString = request.getQueryString();
		queryString = queryString == null ? "" : "?" + queryString;
		logger.info("access url path:" + currentPath + queryString + " |time:" + stopWatch.getTotalTimeMillis());
		stopWatchLocal.set(null);
	}

}
